package com.driving.code.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.driving.code.entity.Question;
import com.driving.code.entity.TUser;
import com.driving.code.entity.UserRole;
import com.driving.code.service.RoleService;
import com.driving.code.service.TUserService;
import com.driving.code.service.UserRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;


public class UserRealm extends AuthorizingRealm {

    @Autowired
    private TUserService tUserService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @Override
    public String getName() {
        return "UserRealm";
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        TUser user = (TUser) SecurityUtils.getSubject().getSession().getAttribute("user");
        Integer userId = user.getUserId();
        List<UserRole> userRoleList = userRoleService.list(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, userId));
        ArrayList<String> roleNameList = new ArrayList<>();
        for (UserRole userRole : userRoleList) {
            roleNameList.add(roleService.getById(userRole.getRoleId()).getRoleName());
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleNameList);
        return simpleAuthorizationInfo;
    }

    /**
     * 获得认证的时候需要的安全数据，数据是从数据库中获取的
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        TUser user = tUserService.getOne(new QueryWrapper<TUser>().lambda().eq(TUser::getUserAccount, principal));
        SimpleAuthenticationInfo simpleAuthenticationInfo = null;
        if (user != null){
            simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getUserAccount(), user.getUserPassword(), ByteSource.Util.bytes(user.getUserSalt()), getName());
            Subject subject = SecurityUtils.getSubject();
            subject.getSession().setAttribute("user",user);
        }
        return simpleAuthenticationInfo;
    }
}
